package com.guangyuan.network.mvc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.guangyuan.network.constants.ProductGroupConstant;
import com.guangyuan.network.constants.ServletConstant;
import com.guangyuan.network.mvc.action.ActionMap;
import com.guangyuan.network.mvc.action.Action;

/**
 * Servlet implementation class SimpleAction
 */
public class SimpleAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(SimpleAction.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SimpleAction() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doHanldeAction(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doHanldeAction(request, response);
	}

	private void doHanldeAction(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("utf-8");
		String actionName = request.getParameter(ServletConstant.HANDLEACTIONNAME);
		String method = request.getParameter(ServletConstant.HANDLEMETHODNAME);
		Action action = ActionMap.getAction(actionName);
		
		System.out.println("actionName : " + actionName + " -- method ：" + method + " -- " + request.getCharacterEncoding());
		Boolean result = false;

		try {
			if (null != action) {
				Method m = action.getClass().getMethod(method, new Class[] {HttpServletRequest.class, HttpServletResponse.class});
				result = (Boolean) m.invoke(action, new Object[] {request, response});
			} else {
				response.sendRedirect("NullAction.vm");
			}
		} catch (SecurityException e) {
			logger.error(e.getMessage());
		} catch (NoSuchMethodException e) {
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  finally {
			if(result) {
				// FIXME! 如果成功了怎样失败了怎样
				response.sendRedirect("addProductGroup.vm");
			}
		}

	}
}
